'''Simple data loader module.

Loads data files from the "data" directory shipped with a game.

Enhancing this to handle caching etc. is left as an exercise for the reader.
'''

import os
import sys
import pygame
from pygame.locals import *

if 'python' in sys.executable:
    data_py = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
else:
    data_py = os.path.abspath(os.path.dirname(sys.executable))
    
data_dir = os.path.normpath(os.path.join(data_py, 'data'))


def filepath(filename):
    '''Determine the path to a file in the data directory.
    '''
    return os.path.join(data_dir, filename)

def load(filename, mode='rb'):
    '''Open a file in the data directory.

    "mode" is passed as the second arg to open().
    '''
    return open(os.path.join(data_dir, filename), mode)

def load_image(name, colorkey=None):
    '''Loads an image from the data dir, with specified colorkey.
       If colorkey is -1 then the colour in the corner of the image will
       be used.
    '''
    fullname = filepath(name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print 'Could not load image:', name
        raise SystemExit, message

    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()

"The following taken from pygame cookbook."

# This class handles sprite sheets
# This was taken from www.scriptefun.com/transcript-2-using
# sprite-sheets-and-drawing-the-background
# I've added some code to fail if the file wasn't found..
# Note: When calling images_at the rect is the format:
# (x, y, x + offset, y + offset)

class Spritesheet(object):
    def __init__(self, filename):
        try:
            self.sheet = pygame.image.load(filepath(filename)).convert()
        except pygame.error, message:
            print 'Unable to load spritesheet image:', filepath(filename)
            raise SystemExit, message

    # Load a specific image from a specific rectangle
    def image_at(self, rectangle, colorkey=None):
        "Loads image from x,y,x+offset,y+offset"
        rect = pygame.Rect(rectangle)
        image = pygame.Surface(rect.size).convert()
        image.blit(self.sheet, (0, 0), rect)
        if colorkey is not None:
            if colorkey is -1:
                colorkey = image.get_at((0,0))
            image.set_colorkey(colorkey, pygame.RLEACCEL)
        return image
    # Load a whole bunch of images and return them as a list
    def images_at(self, rects, colorkey = None):
        "Loads multiple images, supply a list of coordinates"
        imgs = []
        for rect in rects:
            imgs.append(self.image_at(rect, colorkey))
        return imgs
    # Load a whole strip of images
    def load_strip(self, rect, image_count, colorkey = None):
        "Loads a strip of images and returns them as a list"
        tups = []
        for x in range(image_count):
            tups.append((rect[0]+rect[2]*x, rect[1], rect[2], rect[3]))
        return self.images_at(tups, colorkey)

from itertools import chain

def truncline(text, font, maxwidth):
        real=len(text)
        stext=text
        l=font.size(text)[0]
        cut=0
        a=0
        done=1
        old = None
        while l > maxwidth:
            a=a+1
            n=text.rsplit(None, a)[0]
            if stext == n:
                cut += 1
                stext= n[:-cut]
            else:
                stext = n
            l=font.size(stext)[0]
            real=len(stext)
            done=0
        return real, done, stext

def wrapline(text, font, maxwidth):
    done=0
    wrapped=[]

    while not done:
        nl, done, stext=truncline(text, font, maxwidth)
        wrapped.append(stext.strip())
        text=text[nl:]
    return wrapped


def wrap_multi_line(text, font, maxwidth):
    """ returns text taking new lines into account.
    """
    lines = chain(*(wrapline(line, font, maxwidth) for line in text.splitlines()))
    return list(lines)
